package com.chang.bootplus.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chang.bootplus.base.exception.BusException;
import com.chang.bootplus.base.utils.ApiResponse;
import com.chang.bootplus.base.utils.BeanUtil;
import com.chang.bootplus.entity.Menu;
import com.chang.bootplus.entity.RoleMenu;
import com.chang.bootplus.po.MenuPO;
import com.chang.bootplus.service.MenuService;
import com.chang.bootplus.service.RoleMenuService;
import com.chang.bootplus.vo.MenuVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chang
 * @since 2022-01-06
 */
@RestController
@Api(tags = {"菜单信息"})
@CrossOrigin(origins = "*")
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    MenuService menuService;

    @Autowired
    RoleMenuService roleMenuService;


    @PostMapping("add")
    @ApiOperation(httpMethod = "POST", value = "添加菜单")
    public ApiResponse<Void> addmenu(@RequestBody MenuPO menu){
        if (menu.getParentId()==null||menu.getName()==null||menu.getPerms()==null||menu.getType()==null){
            throw new BusException("字段属性为空");
        }
        Menu menu1 = BeanUtil.beanA2beanB(menu, Menu.class);
        menu1.setGmtCreate(LocalDateTime.now());
        menuService.save(menu1);
        return new ApiResponse().setReMsg("添加成功");
    }


    @PostMapping("list")
    @ApiOperation(httpMethod = "POST", value = "展示菜单栏")
    public ApiResponse<MenuVO> listmenu(){
        return menuService.listMenu();
    }

    @PostMapping("update")
    @ApiOperation(httpMethod = "POST", value = "更新菜单栏")
    public ApiResponse<Void> updatemenu(@RequestBody MenuPO menu){
        if (menu.getParentId()==null||menu.getName()==null||menu.getPerms()==null||menu.getType()==null){
            throw new BusException("字段属性为空");
        }
        Menu menu1 = BeanUtil.beanA2beanB(menu, Menu.class);
        menu1.setGmtCreate(LocalDateTime.now());
        menuService.updateById(menu1);
        return new ApiResponse().setReMsg("更新成功");
    }

    @PostMapping("delete")
    @ApiOperation(httpMethod = "POST", value = "删除菜单栏")
    public ApiResponse<Void> deletemenu(@RequestParam Long id){

        int len=menuService.list(new LambdaQueryWrapper<Menu>().eq(Menu::getParentId,id)).size();
        if (len>0){
            throw new BusException("请先删除子菜单");
        }
        Menu menu = menuService.getById(id);
        if (menu==null){
            throw new BusException("当前菜单不存在");
        }

        menuService.removeById(id);
        //删除中间表

        if (new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getMenuId, id)!=null){
            roleMenuService.remove(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getMenuId, id));
        }

        return new ApiResponse().setReMsg("删除成功");
    }


}

